using System;
using System.Reflection;
using System.Threading;

namespace AMFC.Data{
	public class MailMan{
		const string PF_PATH = "Personal Folders";
		public MailMan(){}
		public string SendFax(string userName,string faxTo,string faxNumber,string text,string fileName,string profile,string password){
			Outlook.Application ol = new Outlook.Application();
			Outlook.MailItem mi;
			Outlook.MAPIFolder conts;
			Outlook.MAPIFolder pf;
			Outlook.ContactItem con = null;
			Outlook.Recipient rcp;
		
		  ol.Session.Logon(profile, password, false, false);
			pf = ol.GetNamespace("MAPI").Folders.Item(PF_PATH);

			if( userName.IndexOf("@") > 0 ){
				conts = pf.Folders.Item("Fax Contacts");
				while( null != (con = (Outlook.ContactItem)conts.Items.Find("[FileAs] = \"" + userName + "\"")) )
					if( con != null )con.Delete();
				con = (Outlook.ContactItem)conts.Items.Add(Missing.Value);
				con.FileAs = userName;
				con.Email1Address = userName;
				con.Save();
			}
  
			mi = (Outlook.MailItem)ol.CreateItem(OlItemType.olMailItem);
			mi.To = faxTo + "[fax: " + faxNumber + "]";
			rcp = mi.ReplyRecipients.Add(userName);
			rcp.Resolve();
		  if( !rcp.Resolved )throw new ApplicationException("Recipient \"" + userName + "\" can not be found in address list.");
			if( text != "" )mi.Body = text;
			if( fileName != "" )mi.Attachments.Add(fileName,Missing.Value,Missing.Value,Missing.Value);
  
			mi.Send();
  
			while( pf.Folders.Item("Outbox").Items.Count > 0 )
				Thread.Sleep(0);
				
  		if( con != null )con.Delete();
			
			return "Ok!";
		}
	}
}
